package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.CreateNotification;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class Follow
 */
public class Follow extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Follow() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * A registered user begins following another registered user. Followers of a user are sent a notification whenever
	 * s/he creates a new story fragment. If the follow request is completed successfully, the followed user is sent a
	 * notification.
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int result;
		int followed_id;
		int follower_id;
		boolean followSuccess;
		String username;
		String followedUsername;
		PreparedStatement stmt = null;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();
		String f_requestType = request.getParameter("request_type");

		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				CreateNotification newNotification = new CreateNotification();
				if (f_requestType.equals("Web")) {
					username = (String) request.getSession().getAttribute("username");
					followedUsername = (String) request.getParameter("f_username");
					// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.
					if (username == null) {
						response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
						return;
					}
				} else {
					username = request.getParameter("username");
					followedUsername = request.getParameter("f_username");
				}

				follower_id = Utilities.getUserId(conn, username);
				followed_id = Utilities.getUserId(conn, followedUsername);
				stmt = conn.prepareStatement("INSERT INTO "
						+ TableNames.FOLLOW_TABLE
						+ "(followed_id,follower_id) VALUES(?,?)");
				stmt.setInt(1, followed_id);
				stmt.setInt(2, follower_id);
				result = stmt.executeUpdate();
				/*
				 * If the follow request is completed successfully, the followed user is sent a notification.
				 * Please refer to CreateNotification.java in utils package to get a more detailed description of the
				 * notification system.
				 */
				if (result == 1) {
					followSuccess = true;
					newNotification.createFollowNotification(follower_id,
							followed_id);
				} else {
					followSuccess = false;
				}

				if (f_requestType.equals("Web")) {
					request.setAttribute("followSuccess", followSuccess);
					// After the operation is completed, user is redirected to the profile page of the followed user.
					response.sendRedirect(request.getContextPath() + "/GetProfile?targetname=" + followedUsername);
				} else if (f_requestType.equals("Android")) {
					JSONObject followResultJsonObject = new JSONObject();
					try {
						followResultJsonObject.put("followSuccess",	followSuccess);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(followResultJsonObject.toString());
				} else {
					// HANDLE?
				}
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}
}
